package com.ruoyi.web.controller.uav;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.uav.domain.UavTaskRecord;
import com.ruoyi.uav.domain.UavTaskSteps;
import com.ruoyi.uav.domain.vo.TaskImageData;
import com.ruoyi.uav.domain.vo.TaskInfoData;
import com.ruoyi.uav.domain.vo.TaskSelfDestructData;
import com.ruoyi.uav.domain.vo.TaskThrowData;
import com.ruoyi.uav.service.IUavTaskRecordService;
import com.ruoyi.uav.service.IUavTaskStepsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;


@RestController
@RequestMapping("/uav/qgc")
@Api(value = "qgc数据接收控制层", tags = "qgc数据接收控制层")
public class UavQGCController extends BaseController {

    @Resource
    private IUavTaskStepsService uavTaskStepsService;

    @Resource
    private IUavTaskRecordService uavTaskRecordService;

    @PostMapping("/stepInfo")
    @ApiOperation(value = "新增任务步骤信息", notes = "传入stepInfoData")
    public AjaxResult stepInfo(TaskInfoData stepInfoData) {
        //更新任务完成时间
        UavTaskRecord uavTaskRecord = uavTaskRecordService.getById(stepInfoData.getTaskRecordId());
        uavTaskRecord.setStatus("2");
        Date createTime = uavTaskRecord.getCreateTime();
        Duration duration = Duration.between(createTime.toInstant(), Instant.now()); // 计算两个时间点的差值
        String completeTime = formatDuration(duration); // 转换为分秒格式的字符串
        uavTaskRecord.setCompleteTime(completeTime);
        uavTaskRecordService.updateById(uavTaskRecord);

        UavTaskSteps uavTaskSteps = new UavTaskSteps();
        uavTaskSteps.setStepsInfo(stepInfoData.getTaskSteps());
        uavTaskSteps.setTaskRecordId(stepInfoData.getTaskRecordId());
        uavTaskStepsService.save(uavTaskSteps);

        return success("消息接收成功");
    }

    @PostMapping("/image")
    public AjaxResult image(TaskImageData taskImageData) {

        return success("消息接收成功");
    }

    @PostMapping("throw")
    public AjaxResult throwInfo(TaskThrowData taskThrowData) {

        return success("消息接收成功");
    }

    @PostMapping("selfDestruct")
    public AjaxResult selfDestruct(TaskSelfDestructData taskSelfDestructData) {

        return success("消息接收成功");
    }


    /**
     * 将Duration对象转换为分秒格式的字符串
     * @param duration Duration对象
     * @return 分秒格式的字符串
     */
    private String formatDuration(Duration duration) {
        long minutes = duration.toMinutes();
        long seconds = duration.getSeconds() % 60;

        return String.format("%d分钟%d秒", minutes, seconds);
    }
}
